package com.winai.launcher.view.guide;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.dueeeke.videoplayer.player.VideoView;
import com.ks.projectbasictools.utils.LogUtils;
import com.ks.projectbasictools.utils.ToastKs;
import com.winai.launcher.R;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.utils.cache.PreloadManager;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.winai.launcher.constant.VideoConstant.URL_AD;

/**
 * 作者：康少
 * 时间：2020/3/2
 * 说明：引导页视频
 */
public class GuideVideoActivity extends BaseActivity {

    @BindView(R.id.player)
    VideoView videoView;
    @BindView(R.id.tv_jump)
    TextView tvJump;
    @BindView(R.id.tv_pause)
    TextView tvPause;

    private final String TAG = GuideVideoActivity.class.getSimpleName();
    private Context mContext = this;
    private boolean isReplay;//是否是重播
    private boolean canReplay = false;//是否可以执行重播

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide_video);
        ButterKnife.bind(this);
        String playUrl = PreloadManager.getInstance(this).getPlayUrl(URL_AD);
        videoView.setUrl(playUrl);//设置视频地址
        videoView.setScreenScaleType(VideoView.SCREEN_SCALE_CENTER_CROP);
        StandardVideoController controller = new StandardVideoController(this);
        controller.addDefaultControlComponent(false);
        videoView.setVideoController(controller); //设置控制器
        videoView.setOnStateChangeListener(new VideoView.OnStateChangeListener() {
            @Override
            public void onPlayerStateChanged(int playerState) {

            }

            @Override
            public void onPlayStateChanged(int playState) {
                boolean b = isAPPBroughtToBackground(GuideVideoActivity.this);
                switch (playState) {
                    //调用release方法会回到此状态
                    case VideoView.STATE_ERROR:
                        Log.e(TAG, "STATE_ERROR：播放错误");
                        break;
                    case VideoView.STATE_PREPARING:
                        Log.e(TAG, "STATE_PREPARING：播放准备中…");
                        break;
                    case VideoView.STATE_PREPARED:
                        Log.e(TAG, "STATE_PREPARED：播放准备好了。GuideVideoActivity是否可见 = " + b);
                        if (!b) {
                            videoView.pause();
                        }
                        break;
                    case VideoView.STATE_PLAYING:
                        Log.e(TAG, "STATE_PLAYING：播放中…。GuideVideoActivity是否可见 = " + b);
                        if (!b) {
                            videoView.pause();
                        }
                        break;
                    case VideoView.STATE_PAUSED:
                        Log.e(TAG, "STATE_PAUSED：播放暂停");
                        break;
                    case VideoView.STATE_PLAYBACK_COMPLETED:
                        Log.e(TAG, "STATE_PLAYBACK_COMPLETED：播放完成");
                        break;
                    case VideoView.STATE_BUFFERING:
                        Log.e(TAG, "STATE_BUFFERING：播放正在缓冲…");
                        break;
                    case VideoView.STATE_BUFFERED:
                        Log.e(TAG, "STATE_BUFFERED：播放缓冲完毕。GuideVideoActivity是否可见 = " + b);
                        if (!b) {
                            videoView.pause();
                        }
                        break;
                }
            }
        });
        videoView.start(); //开始播放，不调用则不自动播放
    }

    private boolean play = false;

    public void togglePlay() {
        if (play) {
            tvPause.setVisibility(View.GONE);
            tvJump.setVisibility(View.VISIBLE);
        } else {
            tvPause.setVisibility(View.VISIBLE);
            tvJump.setVisibility(View.GONE);
        }
        play = !play;
    }

    /**
     * @date 2021/2/5
     * @desc 判断当前Activity是否可见
     */
    public static boolean isAPPBroughtToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (topActivity.getClassName().equals(context.getClass().getName())) {
                return true;
            }
        }
        return false;
    }

    @OnClick(R.id.tv_jump)
    public void onViewClicked(View v) {
        if (canIn()) {
            videoView.pause();
            videoView.setVisibility(View.GONE);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startActivity(new Intent(GuideVideoActivity.this, GuideCompleteActivity.class));
                }
            }, 500);
        } else {
            ToastKs.show(mContext, "点太快了，请慢一点");
        }
    }

    private long sTime = 0;//请求的时间
    private boolean canIn() {
        //再次请求时间
        long ct = System.currentTimeMillis();
        if (ct - sTime < 2000 || !canReplay) {
            LogUtils.d("2s内限制重复执行跳转逻辑");
            return false;
        }
        sTime = ct;
        return true;
    }

    /**
     * 说明：勿删！！
     * @return true 放开上滑返回手势，默认true
     */
    public boolean isAllowCustomSliding() {
        return false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        videoView.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        videoView.setVisibility(View.VISIBLE);
        synchronized (this) {
            videoView.resume();
        }
        isReplay = getIntent().getBooleanExtra("isReplay", false);
        if (isReplay) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    canReplay = true;
                }
            }, 5000);
        } else {
            canReplay = true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        videoView.release();
        PreloadManager.getInstance(this).removeAllPreloadTask();
        PreloadManager.getInstance(this).deleteCacheFile(URL_AD);
    }

    @Override
    public void onBackPressed() {
        if (!videoView.onBackPressed()) {
            super.onBackPressed();
        }
    }
}
